<template>
    <nly-content-wrapper>
        <nly-content>
            <div style="margin-top: 40px;">
                <a-tabs @change="callback" v-model="tabKey">
                    <!-- <a-tab-pane key="1" tab="分享方法">
                        <div style="width: 900px;">
                        <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }" class="user-class-dd">
                            <a-form-item label="推广网址">
                            <a-input-search
                                v-model="registerUrl"
                                read-only
                                style="width: 675px"
                                @search="onCopy"
                            >
                                <a-button slot="enterButton">复制</a-button>
                            </a-input-search>
                            <a target="_blank" class="qcShareQQDiv" :href="shareRegisterUrl">分享到QQ</a>
                            </a-form-item>
                            <a-form-item label="推广二维码">
                            <div class="qrcode" id="qrcode" ref="qrCodeUrl"></div>
                            <a @click="downloadQrCode" href="javascript:;" title="下载二维码" class="mr-1">点击下载</a>
                            </a-form-item>
                            <a-form-item label="立即分享">
                            <a-textarea read-only :rows="4" :value="method" />
                            </a-form-item>
                            <a-form-item label="佣金规则">
                            <a-textarea read-only :rows="7" :value="rule" />
                            </a-form-item>
                        </a-form>
                        </div>
                    </a-tab-pane> -->
                    <a-tab-pane key="3" tab="我的客户">
                        <div>
                            <a-form :label-col="{ span: 2 }" :wrapper-col="{ span: 5 }" class="user-class-dd">
                                <a-form-item label="客户名称">
                                    <a-input-search v-model="postData.companyName" style="width: 275px" @search="getShareCrmList">
                                        <a-button slot="enterButton">查询</a-button>
                                    </a-input-search>
                                </a-form-item>
                            </a-form>
                        </div>
                        <a-table :columns="crmColumns" :components="components2" :data-source="crmData" :scroll="{x: 500, y: 500}" style="height: calc(100vh - 16rem);" bordered :pagination="paginationCrm">

                        </a-table>
                    </a-tab-pane>
                    <a-tab-pane key="2" tab="推客">
                        <div>
                            <a-form :label-col="{ span: 2 }" :wrapper-col="{ span: 5 }" class="user-class-dd">
                                <a-form-item label="用户名称">
                                    <a-input-search v-model="postData.realName" style="width: 275px" @search="getShareUserList">
                                        <a-button slot="enterButton">查询</a-button>
                                    </a-input-search>
                                </a-form-item>
                            </a-form>
                        </div>
                        <a-table :columns="columns" :components="components" :data-source="data" :scroll="{ y: 500}" style="height: calc(100vh - 14rem);" bordered :pagination="pagination" @change="onTableChange" @expand="onTableExpand">
                            <template slot="treeSort" slot-scope="text, record">
                                <editable-cell :text="text" @editableChange="onCellChange(record,'treeSort',$event)" :reg="numberReg" />
                            </template>
                            <div slot="leave" slot-scope="text,record,index">
                                {{record.shareUserIds?record.shareUserIds.split(',').length:''}}
                            </div>
                        </a-table>
                    </a-tab-pane>
                    <a-tab-pane key="4" tab="推客关系图">
                        <div style="width:100%;height:600px;">
                            <organization-chart :toggleSiblingsResp="true" :datasource="shareAllData" :pan="true" :zoom="true" @node-click="orgClick"></organization-chart>
                        </div>
                    </a-tab-pane>
                </a-tabs>

            </div>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import { shareInfo, shareUserList, shareCrmList, getSignature, getShareUserAll } from "@/api/personal/userInfo";
import { components } from "@/utils/antTableComponents";
import QRCode from "qrcodejs2";
import { userPageListToTree } from "@/utils/tree";
import VueClipboard from "vue-clipboard2";
import wx from "weixin-js-sdk";
import Vue from "vue";

import OrganizationChart from 'vue-organization-chart';
import 'vue-organization-chart/dist/orgchart.css'

Vue.use(VueClipboard);

export default {
    components: {
        OrganizationChart
    },
    data () {
        const columns = [
            {
                title: "推客姓名",
                dataIndex: "realName",
                key: "realName",
                align: "left",
                width: 120
            },
            {
                title: "级次",
                dataIndex: "shareUserId",
                key: "shareUserId",
                align: "center",
                width: 40,
                scopedSlots: { customRender: 'leave' }
            },
            {
                title: "上级",
                dataIndex: "shareUserName",
                key: "shareUserName",
                width: 120,
                customRender: (text) => {
                    return text ? text : '总部';
                }
            },
            {
                title: "手机号",
                dataIndex: "mobile",
                key: "mobile",
                width: 120
            },
            {
                title: "推客等级",
                dataIndex: "levelName",
                key: "levelName",
                width: 120,
            },
            {
                title: "客户数量",
                dataIndex: "crmCount",
                key: "crmCount",
                width: 120
            },
            {
                title: "总佣金",
                dataIndex: "totalCommission",
                key: "totalCommission",
                width: 120
            },
            {
                title: "加入时间",
                dataIndex: "createDate",
                key: "createDate",
                width: 120
            }
        ];

        const crmColumns = [
            {
                title: "客户信息",
                dataIndex: "companyName",
                key: "companyName",
                align: "left",
                width: 120
            },
            {
                title: "联系人",
                dataIndex: "createBy",
                key: "createBy",
                width: 120
            },
            {
                title: "联系电话",
                dataIndex: "mobile",
                key: "mobile",
                width: 120
            },
            {
                title: "推客信息",
                dataIndex: "shareUserName",
                key: "shareUserName",
                width: 120
            },

            {
                title: "实付金额",
                dataIndex: "salePrice",
                key: "salePrice",
                width: 120,
                customRender: (text, row, index) => {
                    if (text) {
                        return text + "元";
                    }
                }
            },
            {
                title: "交易次数",
                dataIndex: "payCount ",
                key: "payCount ",
                width: 120
            },
            {
                title: "最后交易时间",
                dataIndex: "payDate",
                key: "payDate",
                width: 120
            },
            {
                title: "最后登录时间",
                dataIndex: "loginDate",
                key: "loginDate",
                width: 120
            },
            {
                title: "注册时间",
                dataIndex: "registDate",
                key: "registDate",
                width: 120
            }
        ];
        //表格 头部 可伸缩
        this.components = components(columns);
        this.components2 = components(crmColumns);

        return {
            loading: false,
            haveExpandSet: new Set(),
            dataKeySet: new Set(),
            registerUrl: "", //注册地址
            shareRegisterUrl: "", //分享注册地址
            form: this.$form.createForm(this, { name: "coordinated" }),
            header: { "Access-Token": Vue.ls.get("Access-Token") },
            tabKey: "3",
            columns, //我的团队
            crmColumns, //我的客户
            data: [],
            crmData: [],
            selectIds: [],
            selectedKeys: [],
            postData: {
                current: 1,
                size: 20,
                companyName: "",
                realName: ""
            },
            pagination: {
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                style="height:20px;line-height:20px;"
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            paginationCrm: {
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                size: "small",
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.paginationCrm.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            method: "",
            rule: "",
            shareTitle: "", //分享的标题
            shareRemark: "", //分享描述

            ds: {
                'id': '1',
                'name': 'Lao Lao',
                'title': 'general manager',
                'children': [
                    { 'id': '2', 'name': 'Bo Miao', 'title': 'department manager' },
                    {
                        'id': '3', 'name': 'Su Miao', 'title': 'department manager',
                        'children': [
                            { 'id': '4', 'name': 'Tie Hua', 'title': 'senior engineer' },
                            {
                                'id': '5', 'name': 'Hei Hei', 'title': 'senior engineer',
                                'children': [
                                    { 'id': '6', 'name': 'Pang Pang', 'title': 'engineer' },
                                    { 'id': '7', 'name': 'Xiang Xiang', 'title': 'UE engineer' }
                                ]
                            }
                        ]
                    },
                    { 'id': '8', 'name': 'Hong Miao', 'title': 'department manager' },
                    { 'id': '9', 'name': 'Chun Miao', 'title': 'department manager' }
                ]
            },
            shareAllData: [],
        };
    },
    mounted () {
        //this.getShareInfo();
        this.getShareCrmList();

        //获取推客所有级的数据
        this.getShareAll();
    },
    methods: {
        getShareAll () {
            getShareUserAll().then(res => {
                if (res.code === 200) {
                    res.data.forEach(item => {
                        item.name = item.realName + "( " + item.crmCount + " )";
                        item.title = item.userName;
                    })
                    this.shareAllData = this.treeClass(res.data)[0];
                    console.log(this.shareAllData);
                }
            })
        },

        treeClass (data) {
            console.log(typeof data)
            if (typeof data != 'object') {
                console.error('树形data集合错误');
                return
            }
            let map = new Map();
            data.forEach(item => {
                map.set(item.id, item);
            });
            data.forEach((item, index) => {
                let parentItem = map.get(item.shareUserId);
                if (parentItem) {
                    if (!parentItem.children) {
                        parentItem.children = [item];
                    } else {
                        parentItem.children.push(item);
                    }
                }
            });
            return data;
        },

        orgClick (e) {
            console.log(e);
        },
        //获取分享基本信息
        getShareInfo () {
            shareInfo().then(response => {
                if (response.code == 200) {
                    this.registerUrl = response.data.registerUrl;
                    this.shareTitle = response.data.title;
                    this.shareRemark = response.data.shareRemark;
                    this.shareRegisterUrl = "http://connect.qq.com/widget/shareqq/index.html?url=" + encodeURIComponent(this.registerUrl) + "&title=" + this.shareTitle + "&summary=" +
                        this.shareRemark + "&pics=http%3A%2F%2Fbbs.sibanyun.com%2Flogo.png&site=QQ%E5%88%86%E4%BA%AB&style=102&width=163&height=124&showcount=";
                    this.method = response.data.extensionMethod;
                    this.rule = response.data.commissionRules;
                    this.creatQrCode();
                }
            });
        },
        //获取分享个人列表
        getShareUserList () {
            shareUserList(this.postData).then(response => {
                if (response.code == 200) {
                    const childrenNav = [];
                    const { data } = response;
                    const { records, total, current, size } = data;
                    userPageListToTree(records, childrenNav, 0);
                    this.haveExpandSet.clear();
                    this.dataKeySet.clear();
                    this.dataKeySet = new Set(records.map(f => f.id));
                    this.data = childrenNav;
                    Object.assign(this.pagination, {
                        total
                    });
                }
            });
        },
        //获取分享客户列表
        getShareCrmList () {
            shareCrmList(this.postData).then(response => {
                if (response.code == 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    this.crmData = records;
                    Object.assign(this.pagination, {
                        total
                    });
                }
            });
        },
        //生成二维码
        creatQrCode () {
            let qrcode = new QRCode(this.$refs.qrCodeUrl, {
                text: this.registerUrl, // 需要转换为二维码的内容
                width: 100,
                height: 100,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
        },
        // 点击下载app二维码
        downloadQrCode (name) {
            var canvasData = document
                .getElementById("qrcode")
                .getElementsByTagName("canvas");
            var a = document.createElement("a");
            var event = new MouseEvent("click"); // 创建一个单击事件
            a.href = canvasData[0].toDataURL("image/png");
            a.download = "四班云推广二维码";
            a.click(); // 触发a的单击事件
        },
        //查询table 子集数据
        onTableExpand (expanded, record) {
            console.log(expanded, record);
            if (!expanded || this.haveExpandSet.has(record.id)) return false;
            const postData = {
                current: 1,
                size: -1,
                shareUserId: record.id
            };
            shareUserList(postData)
                .then(response => {
                    console.log(`获取：${record.dictLabel}——的子集`, response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records } = data;
                        records.forEach(item => {
                            if (!this.dataKeySet.has(item.id)) {
                                if (!item.treeLeaf) {
                                    item.children = [];
                                }
                                item.key = item.id;
                                record.children.push(item);
                                this.dataKeySet.add(item.id);
                            }
                        });
                        this.data = [...this.data];
                        this.haveExpandSet.add(record.id);
                    }
                })
                .catch(error => { });
        },
        // 复制
        onCopy () {
            this.$copyText(this.registerUrl)
                .then(res => {
                    this.$message.success("复制成功！");
                })
                .catch(err => {
                    this.$message.error("抱歉，复制失败！");
                });
        },
        //tab切换
        callback (key) {
            console.log(key);
            this.tabKey = key;
            if (key == 2) {
                this.getShareUserList();
            }
            if (key == 3) {
                this.getShareCrmList();
            }
        },
        //table 选中列
        selection (keys, info) {
            this.selectedKeys = keys;
            console.log(info);
            const ids = new Array();
            info.forEach(function (val) {
                ids.push(val.id);
            });
            this.selectIds = ids;
            this.selectedKeys = keys;
        },
        WxShareInfo () {
            getSignature(window.location.href).then(res => {
                localStorage.setItem("jsapi_ticket", res.data);
                console.log(res.data);
                //拿到后端给的这些数据
                let appId = res.data.appId;
                let timestamp = res.data.timestamp;
                let nonceStr = res.data.noncestr;
                let signature = res.data.signature;
                wx.config({
                    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: appId, // 必填，公众号的唯一标识，填自己的！
                    timestamp: timestamp, // 必填，生成签名的时间戳，刚才接口拿到的数据
                    nonceStr: nonceStr, // 必填，生成签名的随机串
                    signature: signature, // 必填，签名，见附录1
                    jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage"]
                });

                const _this = this;
                wx.ready(function () {
                    console.log("开始分享");
                    //分享到朋友圈
                    wx.onMenuShareTimeline({
                        title: _this.shareTitle, // 分享时的标题
                        desc: _this.shareRemark,
                        link: encodeURIComponent(_this.registerUrl), // 分享时的链接
                        imgUrl: "http://bbs.sibanyun.com/logo.png", // 分享时的图标
                        success: function () {
                            console.log("分享成功");
                        },
                        cancel: function () {
                            console.log("取消分享");
                        }
                    });
                    //分享给朋友
                    wx.onMenuShareAppMessage({
                        title: _this.shareTitle,
                        desc: _this.shareRemark,
                        link: encodeURIComponent(_this.registerUrl),
                        imgUrl: "http://bbs.sibanyun.com/logo.png",
                        type: "",
                        dataUrl: "",
                        success: function () {
                            console.log("分享成功");
                        },
                        cancel: function () {
                            console.log("取消分享");
                        }
                    });
                });
            });
        },
        //table分页分享
        onTableChange (pagination, filters, sorter) {
            console.log("pagination", pagination);
            Object.assign(this.postData, {
                current: pagination.current,
                size: pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            if (this.key == 2) {
                this.getShareUserList();
            } else {
                this.getShareCrmList();
            }
        },
        changePageSize (e) {
            const value = e.target.value;
            console.log(this.tabKey);
            if (this.tabKey == 2) {
                const { pagination } = this;
                Object.assign(this.postData, {
                    current: pagination.current,
                    size: pagination.pageSize
                });
                console.log(e, value);
                Object.assign(this.pagination, {
                    pageSize: Number.parseInt(value)
                });
                this.getShareUserList();
            } else {
                const { paginationCrm } = this;
                Object.assign(this.postData, {
                    current: paginationCrm.current,
                    size: paginationCrm.pageSize
                });
                console.log(e, value);
                Object.assign(this.paginationCrm, {
                    pageSize: Number.parseInt(value)
                });
                this.getShareCrmList();
            }
        }
    }
};
</script>
<style>
    .avatar-uploader > .ant-upload {
        width: 110px;
        height: 110px;
    }
    .ant-upload-select-picture-card i {
        font-size: 32px;
        color: #999;
    }
    .ant-upload-select-picture-card .ant-upload-text {
        margin-top: 8px;
        color: #666;
    }
    .user-class-dd .ant-form-item {
        margin-bottom: 2px !important;
    }
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }
    /* .crm-btn {
                                                                                              margin-left: 10px;
                                                                                              margin-bottom: 10px;
                                                                                            } */
</style>